package com.xiaoxie.boot.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoxie.boot.bean.User;
import com.xiaoxie.boot.service.UserService;
import com.xiaoxie.boot.utils.AesUtil;
import com.xiaoxie.boot.utils.DataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author xiaoxie
 * @create 2022-02-03 22:47
 */
@Api(tags = "用户API")
@RestController
@Slf4j
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 添加用户时检查用户名是否存在
     *
     * @param username
     * @return
     */
    @GetMapping("/userExist/{username}")
    @ApiOperation(value = "去重", notes = "添加用户时检查用户名是否存在")
    @ApiOperationSupport(author = "小谢")
    public DataInfo userExist(@PathVariable("username") String username) {
        User user = userService.selectByUserName(username);
        if (user == null) {
            return DataInfo.ok();
        } else {
            return DataInfo.fail("用户名已存在!");
        }
    }

    /**
     * 登录时检查验证码是否正确
     *
     * @param request
     * @param captcha
     * @return
     */
    @GetMapping("/codeExist/{captcha}")
    @ApiOperation(value = "验证码验证", notes = "登录时检查验证码是否正确")
    @ApiOperationSupport(author = "小谢")
    public DataInfo codeExist(HttpServletRequest request, @PathVariable String captcha) {
        System.out.println("传输过来的验证码：" + captcha);
        //判断验证码是否正确（验证码已经放入session）
        HttpSession session = request.getSession();
        String realCode = (String) session.getAttribute("VerifyCode");
        System.out.println("session中的验证码：" + realCode);
        if (realCode.toLowerCase().equals(captcha.toLowerCase())) {
            return DataInfo.ok();
        } else {
            return DataInfo.fail("验证码错误!");
        }
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/loginTo")
    @ApiOperation(value = "登录", notes = "登录")
    @ApiOperationSupport(author = "小谢")
    public DataInfo loginTo(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
        String unm = AesUtil.aesDecrypt(username);
        String pwd = AesUtil.aesDecrypt(password);
        log.info("用户试图以用户名：" + unm + "和密码：" + pwd + "进行登录操作");
        User user = userService.selectUserTypeByUP(unm, pwd);
        HttpSession session = request.getSession();
        if (user != null) {
            if (user.getUserStatus() == 1) {
                log.info("用户正常：" + user.getUsername());
                if (user.getUserType() == 0) {
                    session.setAttribute("id", user.getId());
                    session.setAttribute("name", user.getUsername());
                    log.info("超级管理员" + user.getUsername());
                    return DataInfo.ok();
                } else if (user.getUserType() == 1) {
                    session.setAttribute("id", user.getId());
                    session.setAttribute("name", user.getUsername());
                    log.info("普通管理员" + user.getUsername());
                    return DataInfo.ok();
                } else if (user.getUserType() == 2) {
                    session.setAttribute("id", user.getId());
                    session.setAttribute("name", user.getUsername());
                    log.info("读者" + user.getUsername());
                    return DataInfo.ok();
                } else {
                    return null;
                }
            } else {
                log.info("用户冻结：" + user.getUsername());
                return DataInfo.fail("用户已被冻结");
            }
        } else {
            log.info("用户名或密码错误");
            return DataInfo.fail("用户名或密码错误");
        }
    }

    /**
     * 退出功能
     */
    @GetMapping("/loginOut")
    @ApiOperation(value = "退出", notes = "退出功能")
    @ApiOperationSupport(author = "小谢")
    public DataInfo loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();//注销
        return DataInfo.ok();
    }

    /**
     * 基本资料查询
     *
     * @return
     */
    @RequestMapping("/querySetting")
    @ApiOperation(value = "基本资料查询", notes = "基本资料查询")
    @ApiOperationSupport(author = "小谢")
    public DataInfo setting(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("id");
        User user = userService.selectByPrimaryKey(id);
        return DataInfo.ok("成功", user);
    }


    /**
     * 基本资料保存
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/userSetting")
    @ApiOperation(value = "基本资料保存", notes = "基本资料保存")
    @ApiOperationSupport(author = "小谢")
    public DataInfo userSetting(HttpServletRequest request, @RequestBody User user) {
        HttpSession session = request.getSession();
        Integer id = (Integer) session.getAttribute("id");
        user.setId(id);
        int i = userService.updateByPrimaryKeySelective(user);
        if (i == 1) {
            return DataInfo.ok();
        } else {
            return DataInfo.fail("保存失败");
        }
    }

    /**
     * 修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @PostMapping("/updatePassword")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiOperationSupport(author = "小谢")
    public DataInfo updatePassword(HttpServletRequest request, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        HttpSession session = request.getSession();
        Integer id = (Integer) session.getAttribute("id");
        String name = (String) session.getAttribute("name");
        log.info(name + "试图修改密码");
        User user = userService.selectPasswordById(id);
        if (user.getPassword().equals(oldPassword)) {
            int a = userService.updatePasswordById(id, newPassword);
            if (a == 1) {
                log.info(id + "修改密码成功");
                session.removeAttribute("id");
                session.removeAttribute("name");
                return DataInfo.ok();
            } else {
                log.info(id + "修改密码失败");
                return DataInfo.fail("修改失败");
            }
        } else {
            log.info(id + "修改密码失败");
            return DataInfo.fail("旧密码错误");
        }
    }

    /**
     * 查询登录用户的用户名
     *
     * @param request
     * @return
     */
    @GetMapping("/queryName")
    @ApiOperation(value = "用户名查询", notes = "查询登录用户的用户名")
    @ApiOperationSupport(author = "小谢")
    public DataInfo queryName(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("id");
        User user = userService.selectByPrimaryKey(id);
        return DataInfo.ok("成功", user.getUsername());
    }
}
